<template>
  <el-drawer v-model="state.open" destroy-on-close title="新增题目" @close="close" @open="open">
    <template #default>
      <el-tabs style="margin-bottom: 15px;" type="border-card">
        <el-form ref="editForm" :model="data" :rules="rules" label-width="auto" style="width: calc(70vw)">
          <el-tab-pane label="考试信息">
            <el-form-item label="题型" prop="type">
              <el-button v-if="this.state.type === 'DANXUAN'" disabled type="primary">单选题</el-button>
              <el-button v-else-if="this.state.type === 'DUOXUAN'" disabled type="primary">多选题</el-button>
              <el-button v-else-if="this.state.type === 'TIANKONG'" disabled type="primary">填空题</el-button>
              <el-button v-else-if="this.state.type === 'MINGCIJIESHI'" disabled type="primary">名词解释题</el-button>
              <el-button v-else-if="this.state.type === 'LUNSHU'" disabled type="primary">论述题</el-button>
            </el-form-item>
            <el-alert v-if="this.state.type === 'TIANKONG'" :closable="false" style="margin-bottom: 5px;margin-left: 50px;width: auto" type="warning">
              <span style="font-weight: 700; color: var(--el-color-error)">填空部分</span> 请使用4个下划线代替
              <span style="font-weight: 700; color: var(--el-color-error)">____</span>
            </el-alert>
            <el-form-item label="题目" prop="question">
              <Editor v-model="data.question" :init="{
                resize: false, // 不允许用户调整大小
                language: 'zh-Hans', // 汉化
                branding: false, // 隐藏tinymce右下角水印
                convert_urls: false, // 不自动转换链接地址
                plugins: 'autoresize fullscreen image lists table', // 插件
                menubar: false, // 菜单栏
                statusbar: false, // 状态栏
                max_height: 500,
                autoresize_bottom_margin: 10,
                toolbar: 'image alignleft aligncenter alignright alignjustify lineheight | numlist bullist table | fontsize | forecolor backcolor | bold italic underline strikethrough | superscript subscript | hr | ', // 工具栏
                images_reuse_filename: true,
                font_size_formats: '12px 14px 16px 18px 24px 36px',
                images_upload_handler: this.imageUploadHandler,
                content_style:'p{margin: 0;}body{font-size:14px}',
              }" style="width: 100%;"/>
            </el-form-item>
            <el-divider border-style="dashed" content-position="left" style="margin: 40px 0;">
              <span style="color: #73767a;font-weight: 800">答案区</span>
            </el-divider>
            <div style="padding: 15px;margin:-15px;background: #ecf5ff">
              <template v-for="(answer, index) in data.answers" :key="index">
                <el-form-item :prop="'answers['+index+'].answer'">
                  <template #label>
                    <template v-if="this.state.type === 'DANXUAN' || this.state.type === 'DUOXUAN'">选项{{ String.fromCharCode(64 + index + 1) }}</template>
                    <template v-else-if="this.state.type === 'TIANKONG'">第{{ index + 1 }}空</template>
                    <template v-else-if="this.state.type === 'MINGCIJIESHI' ||this.state.type === 'LUNSHU'">答案{{ index + 1 }}</template>
                  </template>
                  <Editor v-model="answer.answer" :init="{
                resize: false, // 不允许用户调整大小
                language: 'zh-Hans', // 汉化
                branding: false, // 隐藏tinymce右下角水印
                convert_urls: false, // 不自动转换链接地址
                plugins: 'autoresize fullscreen image lists table', // 插件
                menubar: false, // 菜单栏
                statusbar: false, // 状态栏
                max_height: 500,
                autoresize_bottom_margin: 10,
                toolbar: 'image alignleft aligncenter alignright alignjustify lineheight | numlist bullist table | fontsize | forecolor backcolor | bold italic underline strikethrough | superscript subscript | hr | ', // 工具栏
                images_reuse_filename: true,
                font_size_formats: '12px 14px 16px 18px 24px 36px',
                images_upload_handler: this.imageUploadHandler,
                content_style:'p{margin: 0;}body{font-size:14px}',
              }" style="width: 100%;"/>
                </el-form-item>
                <el-form-item :prop="'answers['+index+'].rights'" label=" " style="margin-top: -20px" v-if="this.state.type === 'DANXUAN' || this.state.type === 'DUOXUAN'">
                  <el-switch v-if="this.state.type === 'DANXUAN' || this.state.type === 'DUOXUAN'" v-model="answer.rights" :active-value="true" :inactive-value="false" active-text="正确" inactive-text="错误" inline-prompt @change="answerRightChange(index)"/>
                  <a v-if="data.answers.length > 1" class="op" style="color: var(--el-color-danger-light-3)" @click="deleteAnswer(index)">删除</a>
                  <a v-if="index !==data.answers.length - 1 && this.state.type === 'DANXUAN' || this.state.type === 'DUOXUAN'" class="op" @click="insertAnswer(index);">插入选项</a>
                  <a v-else-if="index !==data.answers.length - 1 && this.state.type === 'TIANKONG'" class="op" @click="insertAnswer(index);">插入填空</a>
                  <a v-else-if="index !==data.answers.length - 1 && (this.state.type === 'MINGCIJIESHI' ||this.state.type === 'LUNSHU')" class="op" @click="insertAnswer(index);">插入答案</a>
                </el-form-item>
              </template>
              <el-form-item label=" ">
                <el-button plain style="width: 100%" type="primary" @click="addAnswer">增加答案</el-button>
              </el-form-item>
            </div>

            <el-divider border-style="dashed" content-position="left" style="margin: 40px 0;">
              <span style="color: #73767a;font-weight: 800">解析区</span></el-divider>
            <div style="padding: 15px;margin:-15px;background: #f0f9eb">
              <el-form-item label="解析" prop="analyzes">
                <Editor v-model="data.analyzes" :init="{
                resize: false, // 不允许用户调整大小
                language: 'zh-Hans', // 汉化
                branding: false, // 隐藏tinymce右下角水印
                convert_urls: false, // 不自动转换链接地址
                plugins: 'autoresize fullscreen image lists table', // 插件
                menubar: false, // 菜单栏
                statusbar: false, // 状态栏
                max_height: 500,
                autoresize_bottom_margin: 10,
                toolbar: 'image alignleft aligncenter alignright alignjustify lineheight | numlist bullist table | fontsize | forecolor backcolor | bold italic underline strikethrough | superscript subscript | hr | ', // 工具栏
                images_reuse_filename: true,
                font_size_formats: '12px 14px 16px 18px 24px 36px',
                images_upload_handler: this.imageUploadHandler,
                content_style:'p{margin: 0;}body{font-size:14px}',
              }" style="width: 100%;"/>
              </el-form-item>
            </div>
          </el-tab-pane>
        </el-form>
      </el-tabs>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="close">取消</el-button>
        <el-popconfirm v-if="state.id" cancel-button-text="否" confirm-button-text="是" title="确定删除该题目?" width="250" @confirm="del">
          <template #reference>
            <el-button type='danger'>删除</el-button>
          </template>
        </el-popconfirm>
        <el-button v-if="state.id" type="warning" @click="upsert">更新</el-button>
        <el-button v-else type="primary" @click="upsert">保存</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script>
import Editor from '@tinymce/tinymce-vue'

export default {
  name: "Create",
  props: ['state'],
  components: {Editor},
  data() {
    return {
      data: {
        question: null,
        analyzes: null,
        answers: []
      },
      rules: {
      },
      imageUploadHandler: (blobInfo, progress) => new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.open('POST', import.meta.env.VITE_API_PREFIX + '/image/upload');
        xhr.setRequestHeader('X-Token', localStorage.getItem('X-Token'))

        xhr.upload.onprogress = (e) => {
          progress(e.loaded / e.total * 100);
        };

        xhr.onload = () => {
          if (xhr.status === 200) return resolve(JSON.parse(xhr.responseText).data);
          if (xhr.status === 401) return this.$router.push('/login')
          reject('图片上传失败: ' + xhr.status);
        };

        xhr.onerror = () => {
          reject('图片上传失败: ' + xhr.status);
        };

        const formData = new FormData();
        formData.append('file', blobInfo.blob(), blobInfo.filename());
        xhr.send(formData);
      })
    }
  },
  methods: {
    async open() {
      if (this.state.id) {
        let question = await this.post('/question/get', {id: this.state.id});
        this.data.question = question.question;
        this.data.answers =  question.answers
        return
      }
      if (this.state.type === 'DANXUAN' || this.state.type === 'DUOXUAN') {
        this.data.answers = [{answer: '', rights: false}, {answer: '', rights: false}, {answer: '', rights: false}, {
          answer: '',
          rights: false
        }]
        return
      }
      if (this.state.type === 'TIANKONG' || this.state.type === 'LUNSHU' || this.state.type === 'MINGCIJIESHI') {
        this.data.answers = [{answer: '', rights: true}]
      }
    },
    async upsert() {
      await this.$refs['editForm'].validate(async (valid, fields) => {
        if (!valid) return
        if ((this.state.type === 'DANXUAN' || this.state.type === 'DUOXUAN') && this.data.answers.filter(answer => answer.rights).length === 0) {
          return ElNotification({
            type: 'error',
            duration: 3000,
            title: '信息不完整',
            message: "请至少提供一个正确选项"
          });
        }
        await this.post('/question/upsert', {
          id: this.state.id,
          question: this.data.question,
          type: this.state.type,
          basicCode: this.state.basicCode,
          analyzes: this.data.analyzes,
          answers: this.data.answers
        });
        this.$emit('updated', {del: false})
        this.close()
      })
    },
    async del() {
      await this.post('/question/delete', {
        id: this.state.id,
      });
      this.$emit('updated', {del: true, id: this.state.id})
      this.close()
    },
    close() {
      this.state.open = false
      this.$refs['editForm'].resetFields()
      this.data.answers = []
    },
    deleteAnswer(index) {
      this.data.answers.splice(index, 1)
    },
    insertAnswer(index) {
      if (this.state.type === 'DANXUAN' || this.state.type === 'DUOXUAN') {
        this.data.answers.splice(index + 1, 0, {answer: '', rights: false});
        return
      }
      if (this.state.type === 'TIANKONG' || this.state.type === 'LUNSHU' || this.state.type === 'MINGCIJIESHI') {
        this.data.answers.splice(index + 1, 0, {answer: '', rights: true});
      }
    },
    addAnswer() {
      if (this.state.type === 'TIANKONG' || this.state.type === 'LUNSHU' || this.state.type === 'MINGCIJIESHI') {
        return this.data.answers.push({answer: '', rights: true})
      }
      this.data.answers.push({answer: '', rights: false})
    },
    answerRightChange(index) {
      if (this.state.type !== 'DANXUAN' || !this.data.answers[index].rights) return
      this.data.answers.forEach((answer, i) => {
        answer.rights = i === index
      });
    },
  }
}
</script>

<style scoped>
:deep(.mce-content-body p) {
  margin-top: 50px !important;
}

.op {
  font-size: 12px !important;
  line-height: 0;
  padding: 10px 5px;
  border-radius: 20px;
  margin-left: 5px;
}
</style>